package com.yupi.springbootinit.job.once;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.otter.canal.client.CanalConnector;
import com.alibaba.otter.canal.client.CanalConnectors;
import com.alibaba.otter.canal.common.utils.AddressUtils;
import com.alibaba.otter.canal.protocol.CanalEntry;
import com.alibaba.otter.canal.protocol.Message;
import com.yupi.springbootinit.esdao.PostEsDao;
import com.yupi.springbootinit.model.dto.post.PostEsDTO;
import com.yupi.springbootinit.model.entity.Post;
import com.yupi.springbootinit.service.PostService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.net.InetSocketAddress;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

// 取消 @Component 注释后, 每次启动 SpringBoot 项目会执行一次 run 方法
@Component
@Slf4j
public class CanalRunner implements CommandLineRunner {

    @Resource
    private PostEsDao postEsDao;

    @Value("${canal-monitor-mysql.hostname}")
    String canalMonitorHost;

    @Value("${canal-monitor-mysql.port}")
    Integer canalMonitorPort;

    @Value("${canal-monitor-mysql.tableName}")
    String canalMonitorTableName;

    private final static int BATCH_SIZE = 10000;

    @Override
    public void run(String[] args) {
        // 创建链接
        CanalConnector connector = CanalConnectors.newSingleConnector(new InetSocketAddress(AddressUtils.getHostIp(),
                11111), "example", "", "");
        int batchSize = 1000;
        int emptyCount = 0;
        try {
            connector.connect();
            connector.subscribe(".*\\..*");
            connector.rollback();
            while (true) {
                Message message = connector.getWithoutAck(batchSize); // 获取指定数量的数据
                long batchId = message.getId();
                int size = message.getEntries().size();
                if (batchId == -1 || size == 0) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                    }
                } else {
                    // System.out.printf("message[batchId=%s,size=%s] \n", batchId, size);
                    handleDATAChange(message.getEntries());
                }

                connector.ack(batchId); // 提交确认
                // connector.rollback(batchId); // 处理失败, 回滚数据
            }

        } finally {
            connector.disconnect();
        }
    }

    private void handleDATAChange(List<CanalEntry.Entry> entrys) {
        for (CanalEntry.Entry entry : entrys) {
            //如果是事务头或者尾部则跳过
            if (entry.getEntryType() == CanalEntry.EntryType.TRANSACTIONBEGIN || entry.getEntryType() == CanalEntry.EntryType.TRANSACTIONEND) {
                continue;
            }
            //获取表名
            CanalEntry.RowChange rowChage = null;
            try {
                //反序列化
                rowChage = CanalEntry.RowChange.parseFrom(entry.getStoreValue());
            } catch (Exception e) {
                throw new RuntimeException("ERROR ## parser of eromanga-event has an error , data:" + entry.toString(),
                        e);
            }
            //获取操作类型
            CanalEntry.EventType eventType = rowChage.getEventType();
            System.out.println(String.format("================&gt; binlog[%s:%s] , name[%s,%s] , eventType : %s",
                    entry.getHeader().getLogfileName(), entry.getHeader().getLogfileOffset(),
                    entry.getHeader().getSchemaName(), entry.getHeader().getTableName(),
                    eventType));
            //获取行数据
            for (CanalEntry.RowData rowData : rowChage.getRowDatasList()) {
                //如果是删除操作
                if (eventType == CanalEntry.EventType.DELETE) {
                    //打印变化的数据
                    System.out.println("删除了数据");
                    deleteFromEs(rowData.getBeforeColumnsList());
                    //如果是插入操作
                } else if (eventType == CanalEntry.EventType.INSERT) {
                    //打印变化的数据
                    insertToEs(rowData.getAfterColumnsList());
                    //如果是更新操作
                } else {
                    System.out.println("-------&gt; before");
                    deleteFromEs(rowData.getBeforeColumnsList());
                    System.out.println("-------&gt; after");
                    insertToEs(rowData.getAfterColumnsList());
                }
            }
        }
    }

    private void insertToEs(List<CanalEntry.Column> afterColumnsList) {
        PostEsDTO postEsDTO = new PostEsDTO();
        postEsDTO.setId(Long.valueOf(afterColumnsList.get(0).getValue()));
        postEsDTO.setTitle(afterColumnsList.get(1).getValue());


        postEsDTO.setContent(afterColumnsList.get(2).getValue());
        String tags = afterColumnsList.get(3).getValue();
        //将String数组转化为列表
        List<String> tagList = new ArrayList<>();
        if (tags.length() > 2) {
            for (String tag : tags.substring(1, tags.length() - 1).split(",")) {
                tagList.add(tag.substring(1, tag.length() - 1));
            }
            postEsDTO.setTags(tagList);
        }
        postEsDTO.setThumbNum(Integer.valueOf(afterColumnsList.get(4).getValue()));
        postEsDTO.setFavourNum(Integer.valueOf(afterColumnsList.get(5).getValue()));
        postEsDTO.setUserId(Long.valueOf(afterColumnsList.get(6).getValue()));
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        try {
            postEsDTO.setCreateTime(simpleDateFormat.parse(afterColumnsList.get(7).getValue()));
            postEsDTO.setUpdateTime(simpleDateFormat.parse(afterColumnsList.get(8).getValue()));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        postEsDao.save(postEsDTO);


    }

    private void deleteFromEs(List<CanalEntry.Column> beforeColumnsList) {
        postEsDao.deleteById(Long.valueOf(beforeColumnsList.get(0).getValue()));
    }


}